package com.anb.net;

import com.anb.common.Utils;

import java.lang.reflect.Method;
import java.lang.reflect.Modifier;

public class ClassMethodCmdHandler extends MethodCmdHandler {

    private String[] namespaces;

    public ClassMethodCmdHandler(String[] namespaces) {
        this.namespaces = namespaces;
    }

    public ClassMethodCmdHandler(String namespace) {
        this(new String[] { namespace });
    }

    @Override
    public void prepare() throws Exception {
        String[] splits = name.split("\\.");
        if (splits.length != 2) {
            throw new Exception("command " + name + " not in format of <class>.<method>");
        }
        method = getMethod(splits[0], splits[1], namespaces);
    }

    private static Method getMethod(String className, String methodName, String[] namespaces) throws Exception {
        //String methodName1 = Utils.decapitalize(methodName);
        Class<?> clazz = Utils.getClass(className, namespaces);
        for (Method method : clazz.getMethods()) {
            String name = method.getName();
            if (!name.equals(methodName)
                    /*&& !name.equals(methodName1)*/
                    ) {
                continue;
            }
            if (!Modifier.isStatic(method.getModifiers())) {
                continue;
            }
            return method;
        }
        throw new Exception("static method not found for " + className + "." + methodName);
    }
}
